package com.slfx.open.api.utils;

import java.util.Base64;


import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

/**使用hutool工具类中的rsa工具*/
public class RSAHutoolUtil {
	/**
	 * 获取公钥私钥密钥对
	 * */
	static String getKeyPair(RSA rsa){
		StringBuilder rtnStb=new StringBuilder();
		//获得私钥
//		System.out.println(rsa.getPrivateKey());
		rtnStb.append("privateKey: ");
		rtnStb.append(rsa.getPrivateKeyBase64());
		rtnStb.append("\n");
		//获得公钥
//		System.out.println(rsa.getPublicKey());
		rtnStb.append("publicKey: ");
		rtnStb.append(rsa.getPublicKeyBase64());
		return rtnStb.toString();
	}
	
	//加密
	public static String getEncryptString(String str, RSA rsa){
		byte[] encrypt = rsa.encrypt(StrUtil.bytes(str, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
		return Base64.getEncoder().encodeToString(encrypt);
	}
	
	//解密
	public static String getDecryptString(String str, RSA rsa){
		byte[] aByte = Base64.getDecoder().decode(str);
		byte[] decrypt = rsa.decrypt(aByte, KeyType.PrivateKey);
		return new String(decrypt, CharsetUtil.CHARSET_UTF_8);
	}
	
	public static void main(String[] args) {
		System.out.println(getKeyPair(new RSA()));

		String priKey="MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKy5YfzOCX9IjdKemQGaVg0gfZcM0RJ5WcPfWorIw9Rpd0ZPkjMEW8boHbq7LHRgclGWSJe8je4k+W7hh51IjS0g0Dxg0ulIqVEtHrY0KxVJhtWN0ygPYq+Yyu3iseX7KxP2/psOojggr2KPJ6csJvQiVovXzyYY7heueuXmEQkRAgMBAAECgYA1FwY3Xl0s8nAlPPpqs7Wfc00nEJlyxDoDKrP51Jvcvk4bHnohlEVhbhc1PjL70mlRCpBlk19Mw7CnlErK3XIG2xVarhWCNnf9tml8/vQd871SU3qMngtwmpI5b26bj+CW3osmmFp2fh6ChfGAel74OCvPP8hth4cHMDl304oNAQJBAOhb2mNJzqzakQVx18IN2dV2gtiqS1gNGff6gvxepMwd2jq1KMQp5uD+aLwHf5DwLEOpJpV2wPKJDuM3AW/6n4UCQQC+TECZfeqsJe24+A9XqpcO3M1PH+oG8IsugNy/Lre/eBgyMjNqYVrmXP1tnBupdFvOxBMq3TUpyyAV4ZQufUsdAkEAlKEUq8gtdLIGa8YrbgywF3RMNE2SDkurHc1XdhkQLyS1UDJLVlc7QRZbZlMhjVOj7M/JR3gD6eAz7rFjsP5OhQJAGWa8SMDSDmCRttsF0UHoIAfBMAqmhn6dVXvF+48U3+377NdenZiZNZ68BWGNH7V0e8kYdeRJMGb4xXLzALGg0QJBAKy+RPYOO1lfaoYXm0EjzXuleONG4Yw4Mya+rEuax0ztgkU8d0of8cJ5SrnBCeGmHjSfCnCPY9STVir1OPxWauM=";
		String pubKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsuWH8zgl/SI3SnpkBmlYNIH2XDNESeVnD31qKyMPUaXdGT5IzBFvG6B26uyx0YHJRlkiXvI3uJPlu4YedSI0tINA8YNLpSKlRLR62NCsVSYbVjdMoD2KvmMrt4rHl+ysT9v6bDqI4IK9ijyenLCb0IlaL188mGO4Xrnrl5hEJEQIDAQAB";
		RSA rsa = new RSA(priKey, pubKey);
		String plainTxt="123";
		String encryptTxt=getEncryptString(plainTxt, rsa);
		//WAogiaXAmVDtSQ6wBDcHNc/k8KzFC/pM4wJgIDENogx8HQWoqzRk5rIJQGe11vHrTqZYEc1cE64DxCKYVgVqNc9zFePkuOncNznphznvkx0zmRm5Y/uicdmGUOPryuDI6Iikji6/XMZiD/kF81ZaowzUfy2GQyHMQ6rLiVFKXJg=
		System.out.println(encryptTxt);
		String decryptTxt=getDecryptString(encryptTxt, rsa);
		//123
		System.out.println(decryptTxt);
	}
}

